<template>
  <view class="city-select-page">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="back-btn" @click="goBack">
        <image src="/static/img/xiangzuojiantou.png" mode="" style="width: 25px;height: 25px;"></image>
      </view>
      <text class="title">城市选择</text>
      <view class="empty-btn"></view>
    </view>

    <!-- 当前定位 -->
    <view class="section">
      <text class="section-label">当前定位</text>
      <view class="city-item" @click="selectCity({label: '南京', value: 'AREA_2bc437ca-b3d2-5c3c', pinyin: 'nanjing', short: 'nj'}, true)">
        <text>南京</text>
        <view class="selected-icon"></view>
      </view>
    </view>

    <!-- 热门城市 -->
    <view class="section">
      <text class="section-label">热门城市</text>
      <view class="city-list hot-cities">
        <view class="city-item" v-for="city in hotCiitem" :key="city.value" @click="selectCity(city)">
          <text>{{ city.label }}</text>
        </view>
      </view>
    </view>

    <!-- 字母索引城市 -->
    <view class="section">
      <view class="letter-group" v-for="(cities, letter) in groupedCities" :key="letter" :id="`letter-${letter}`">
        <text class="letter-label" :data-letter="letter">{{ letter }}</text>
        <view class="city-list">
          <view class="city-item" v-for="city in cities" :key="city.value" @click="selectCity(city)">
            <text>{{ city.label }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 右侧字母导航 -->
    <view class="letter-nav">
      <text 
        class="nav-letter" 
        v-for="letter in letters" 
        :key="letter" 
        @click="scrollToLetter(letter)"
      >
        {{ letter }}
      </text>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue';

// 热门城市数据
const hotCiitem = ref([])

// 城市名称
const rawCityData = ref([]);
// 安装字母分组
const groupedCities = ref({});

// 城市名称接口
uni.request({
	url:"http://localhost:8080/area/city?level=1",
	method:'GET',
	success: (res) => {
		console.log('城市数据:', res);
		if (res.data && res.data.body) {
			rawCityData.value = res.data.body;
			// 按首字母分组城市数据
			groupCitiesByFirstLetter();
		}
	}
});

// 热门城市
uni.request({
	url:"http://localhost:8080/area/hot",
	method:'GET',
	success: (res) => {
		console.log('城市数据:', res);
		if (res.data && res.data.body) {
			hotCiitem.value = res.data.body;
			// 按首字母分组城市数据
			// groupCitiesByFirstLetter();
		}
	}
});

// 按首字母分组城市数据
const groupCitiesByFirstLetter = () => {
	const groups = {};
	
	// 确保 rawCityData 是数组
	if (Array.isArray(rawCityData.value)) {
		rawCityData.value.forEach(city => {
			// 从拼音中获取首字母并转换为大写
			if (city.pinyin && city.pinyin.length > 0) {
				const firstLetter = city.pinyin.charAt(0).toUpperCase();
				if (!groups[firstLetter]) {
					groups[firstLetter] = [];
				}
				groups[firstLetter].push(city);
			}
		});
	}
	
	// 按字母顺序排序
	const sortedGroups = {};
	Object.keys(groups).sort().forEach(letter => {
		sortedGroups[letter] = groups[letter];
	});
	
	groupedCities.value = sortedGroups;
};

// 右侧字母导航数据
const letters = ref(['A', 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'Q', 'S', 'T', 'W', 'X', 'Y', 'Z']);

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 选择城市
const selectCity = (city, isCurrent = false) => {
  // 标准化城市数据格式
  let cityData;
  
  if (typeof city === 'string') {
    // 处理字符串类型的城市（如当前定位）
    cityData = {
      label: city,
      value: city === '南京' ? 'AREA_2bc437ca-b3d2-5c3c' : `AREA_${city.toLowerCase()}`,
      pinyin: city.toLowerCase(),
      short: city.charAt(0).toLowerCase()
    };
  } else {
    // 使用对象类型的城市数据
    cityData = city;
  }
  
  console.log('选择的城市:', cityData);
  
  // 触发城市选择事件，传递城市数据
  uni.$emit('citySelected', cityData);
  
  // 直接返回上一页
  uni.navigateBack();
};

// 滚动到指定字母区域
const scrollToLetter = (letter) => {
  // 查找对应字母的元素
  const selector = `#letter-${letter}`;
  const query = uni.createSelectorQuery();
  
  query.select(selector).boundingClientRect((rect) => {
    if (rect) {
      // 获取页面滚动距离
      uni.createSelectorQuery().selectViewport().scrollOffset(({ scrollTop }) => {
        // 计算需要滚动的距离
        const distance = scrollTop + rect.top - 50; // 50是导航栏高度的估计值
        uni.pageScrollTo({
          scrollTop: distance,
          duration: 300
        });
      }).exec();
    }
  }).exec();
};
</script>

<style scoped>
.city-select-page {
  background-color: #fff;
  height: 100vh;
  overflow-y: scroll;
}

/* 导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  height: 44px;
  border-bottom: 1px solid #eee;
  padding: 0 15px;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
}
.back-btn {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.title {
  flex: 1;
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  color: #07c160;
}
.empty-btn {
  width: 30px;
}

/* 模块通用样式 */
.section {
  margin-bottom: 20px;
}
.section-label {
  font-size: 14px;
  color: #07c160;
  margin-bottom: 10px;
  display: block;
  padding: 10px 15px 0;
}

/* 城市列表 */
.city-list {
  padding: 0 15px;
}

/* 热门城市网格布局 */
.hot-cities {
  display: flex;
  flex-wrap: wrap;
}

.hot-cities .city-item {
  width: 33.33%;
  height: auto;
  padding: 10px 0;
  border-bottom: none;
  justify-content: flex-start;
}

/* 城市项 */
.city-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 44px;
  border-bottom: 1px solid #f5f5f5;
}
.city-item text {
  font-size: 16px;
  color: #333;
}
.selected-icon {
  width: 16px;
  height: 16px;
  background-color: #07c160;
  border-radius: 50%;
  position: relative;
}
.selected-icon::after {
  content: '';
  position: absolute;
  top: 4px;
  left: 7px;
  width: 3px;
  height: 8px;
  border-right: 2px solid white;
  border-bottom: 2px solid white;
  transform: rotate(45deg);
}

/* 字母分组 */
.letter-label {
  font-size: 14px;
  color: #07c160;
  margin-bottom: 0;
  padding: 10px 15px 5px;
  background-color: #f8f8f8;
}

/* 右侧字母导航 */
.letter-nav {
  position: fixed;
  right: 5px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  padding: 5px 2px;
}
.nav-letter {
  font-size: 12px;
  color: #07c160;
  padding: 3px 2px;
  width: 20px;
  text-align: center;
}
.nav-letter:active {
  color: #00a854;
  background-color: rgba(7, 193, 96, 0.2);
  border-radius: 4px;
}
</style>